package com.sina.rd.dsp.nedis;

import com.sina.rd.dsp.server.RouteMap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: xinrong3
 * Date: 14-4-3
 * Time: 上午11:42
 */
public class NedisService implements Runnable{
    public static final Log LOG = LogFactory.getLog(NedisService.class);

    private final Properties prop;

    private final int port;
    private RouteMap routeMap;

    public NedisService(Properties properties,RouteMap map){
        this.prop=properties;
        this.routeMap=map;
        port=Integer.parseInt(prop.getProperty("cluster.nedis.port","6789"));
    }

    @Override
    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        //初始化channel的辅助类，为具体子类提供公共数据结构
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup,workerGroup);
        bootstrap.channel(NioServerSocketChannel.class)
                .childHandler(new NedisServerChannelInitializer(prop,routeMap))
                .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = null; // (7)
        try {
            f = bootstrap.bind(port).sync();
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public void start(){
        this.run();
    }

//    public static void main(String ...args) {
//        Properties p=new Properties();
//        p.put(HConstants.ZOOKEEPER_QUORUM,args[0]);
//        p.put("cluster.name",args[1]);
//        NedisService ns=new NedisService(p,new RouteMap());
//        ns.run();
//    }
}
